package com.tian.core.utils;


import cn.hutool.json.JSONUtil;
import com.tian.core.exceptions.CheckException;
import com.tian.core.lang.Constant;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Shiro Filter 工具类
 */
public class ShiroFilterUtils {

	/**
	 * 是否是Ajax请求
	 * @param request
	 * @return
	 */
	public static boolean isAjax(ServletRequest request){
		return "XMLHttpRequest".equalsIgnoreCase(((HttpServletRequest) request).getHeader("X-Requested-With"));
	}

	/**
	 * response 输出JSON
	 * @param response
	 * @param resultMap
	 * @throws IOException
	 */
	public static void out(HttpServletResponse response, Map<String, Object> resultMap){

		PrintWriter out = null;
		try {
			response.setHeader("Content-type", "text/html;charset=UTF-8");
			response.setCharacterEncoding("UTF-8");
			out = response.getWriter();
			out.println(JSONUtil.toJsonStr(resultMap));
		} catch (Exception e) {
			throw new CheckException(Constant.ERROR_RESP_MSG);
		}finally{
			if(null != out){
				out.flush();
				out.close();
			}
		}
	}
}
